package com.tsing.mvc.controller;

import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.support.ServletUriComponentsBuilder;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Base64;
import java.util.HashMap;
import java.util.Map;

/**
 * PDF文件控制器
 * 提供PDF文件的URL和Base64数据接口
 */
@RestController
@RequestMapping("/api/pdf")
@CrossOrigin(origins = "*") // 允许跨域访问
public class PdfController {

    // 固定的PDF文件路径
    private static final String PDF_FILE_PATH = "D:\\workpace\\note\\大数据开发\\java.pdf";
    
    // 静态文件访问的基础URL
    private static final String STATIC_BASE_URL = "/static/pdf/";

    /**
     * 根据cataLogId获取PDF文件的URL
     * 
     * @param cataLogId 目录ID
     * @return 包含PDF URL的响应
     */
    @GetMapping("/url/{cataLogId}")
    public ResponseEntity<Map<String, Object>> getPdfUrl(@PathVariable String cataLogId) {
        Map<String, Object> response = new HashMap<>();
        
        try {
            // 检查文件是否存在
            File pdfFile = new File(PDF_FILE_PATH);
            if (!pdfFile.exists()) {
                response.put("success", false);
                response.put("message", "PDF文件不存在");
                return ResponseEntity.status(HttpStatus.NOT_FOUND).body(response);
            }
            
            // 构建PDF文件的访问URL
            String pdfUrl = ServletUriComponentsBuilder.fromCurrentContextPath()
                    .path(STATIC_BASE_URL)
                    .path("java.pdf")
                    .build()
                    .toUriString();
            
            // 构建返回数据
            Map<String, Object> data = new HashMap<>();
            data.put("type", "url");
            data.put("url", pdfUrl);
            data.put("cataLogId", cataLogId);
            data.put("fileName", "java.pdf");
            
            response.put("success", true);
            response.put("data", data);
            response.put("message", "获取PDF URL成功");
            
            return ResponseEntity.ok(response);
            
        } catch (Exception e) {
            response.put("success", false);
            response.put("message", "获取PDF URL失败: " + e.getMessage());
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(response);
        }
    }

    /**
     * 根据cataLogId获取PDF文件的Base64数据
     * 
     * @param cataLogId 目录ID
     * @return 包含PDF Base64数据的响应
     */
    @GetMapping("/base64/{cataLogId}")
    public ResponseEntity<Map<String, Object>> getPdfBase64(@PathVariable String cataLogId) {
        Map<String, Object> response = new HashMap<>();
        
        try {
            // 检查文件是否存在
            Path pdfPath = Paths.get(PDF_FILE_PATH);
            if (!Files.exists(pdfPath)) {
                response.put("success", false);
                response.put("message", "PDF文件不存在");
                return ResponseEntity.status(HttpStatus.NOT_FOUND).body(response);
            }
            
            // 读取PDF文件并转换为Base64
            byte[] pdfBytes = Files.readAllBytes(pdfPath);
            String base64Data = Base64.getEncoder().encodeToString(pdfBytes);
            
            // 构建返回数据
            Map<String, Object> data = new HashMap<>();
            data.put("type", "base64");
            data.put("data", base64Data);
            data.put("cataLogId", cataLogId);
            data.put("fileName", "java.pdf");
            data.put("fileSize", pdfBytes.length);
            
            response.put("success", true);
            response.put("data", data);
            response.put("message", "获取PDF Base64数据成功");
            
            return ResponseEntity.ok(response);
            
        } catch (IOException e) {
            response.put("success", false);
            response.put("message", "读取PDF文件失败: " + e.getMessage());
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(response);
        } catch (Exception e) {
            response.put("success", false);
            response.put("message", "获取PDF Base64数据失败: " + e.getMessage());
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(response);
        }
    }

    /**
     * 根据cataLogId获取PDF文件（统一接口，根据参数决定返回格式）
     * 
     * @param cataLogId 目录ID
     * @param format 返回格式：url 或 base64，默认为url
     * @return 包含PDF数据的响应
     */
    @GetMapping("/{cataLogId}")
    public ResponseEntity<Map<String, Object>> getPdf(
            @PathVariable String cataLogId,
            @RequestParam(defaultValue = "url") String format) {
        
        if ("base64".equalsIgnoreCase(format)) {
            return getPdfBase64(cataLogId);
        } else {
            return getPdfUrl(cataLogId);
        }
    }

    /**
     * 直接下载PDF文件
     * 
     * @param cataLogId 目录ID
     * @return PDF文件流
     */
    @GetMapping("/download/{cataLogId}")
    public ResponseEntity<byte[]> downloadPdf(@PathVariable String cataLogId) {
        try {
            // 检查文件是否存在
            Path pdfPath = Paths.get(PDF_FILE_PATH);
            if (!Files.exists(pdfPath)) {
                return ResponseEntity.status(HttpStatus.NOT_FOUND).build();
            }
            
            // 读取PDF文件
            byte[] pdfBytes = Files.readAllBytes(pdfPath);
            
            // 设置响应头
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_PDF);
            headers.setContentDispositionFormData("attachment", "java.pdf");
            headers.setContentLength(pdfBytes.length);
            
            return ResponseEntity.ok()
                    .headers(headers)
                    .body(pdfBytes);
                    
        } catch (IOException e) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build();
        }
    }

    /**
     * 检查PDF文件是否存在
     * 
     * @param cataLogId 目录ID
     * @return 文件状态信息
     */
    @GetMapping("/status/{cataLogId}")
    public ResponseEntity<Map<String, Object>> checkPdfStatus(@PathVariable String cataLogId) {
        Map<String, Object> response = new HashMap<>();
        
        try {
            File pdfFile = new File(PDF_FILE_PATH);
            
            Map<String, Object> data = new HashMap<>();
            data.put("exists", pdfFile.exists());
            data.put("cataLogId", cataLogId);
            data.put("filePath", PDF_FILE_PATH);
            
            if (pdfFile.exists()) {
                data.put("fileSize", pdfFile.length());
                data.put("lastModified", pdfFile.lastModified());
                data.put("fileName", pdfFile.getName());
            }
            
            response.put("success", true);
            response.put("data", data);
            response.put("message", "检查PDF文件状态成功");
            
            return ResponseEntity.ok(response);
            
        } catch (Exception e) {
            response.put("success", false);
            response.put("message", "检查PDF文件状态失败: " + e.getMessage());
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(response);
        }
    }
} 